import { post, get } from '../../utils/request'

Page({
  data: {
    username: '',
    password: '',
    userTypes: ['普通用户', '维修工'],
    userTypeIndex: null,
    canIUseGetUserProfile: false
  },

  onLoad() {
    // 检查微信版本，判断是否支持 wx.getUserProfile
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    // 自动填充用户信息（假设已存储在本地）
    const userInfo = wx.getStorageSync('userInfo') || {};
    // 这里可以根据需要填充用户名等，但微信登录通常不预填充
  },

  onInput(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [field]: e.detail.value
    })
  },

  onUserTypeChange(e) {
    this.setData({
      userTypeIndex: e.detail.value
    })
  },

  // 新增：微信一键登录（推荐方式）
  handleWeChatLogin() {
    console.log('开始微信登录流程');
    
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (userRes) => {
        console.log('获取用户信息成功:', userRes);
        
        wx.login({
          success: (loginRes) => {
            console.log('wx.login成功:', loginRes);
            
            if (loginRes.code) {
              console.log('获取到code:', loginRes.code);
              
              wx.showLoading({
                title: '登录中...',
                mask: true
              });
              
              const requestData = {
                code: loginRes.code,
                rawData: userRes.rawData,
                signature: userRes.signature,
                encryptedData: userRes.encryptedData,
                iv: userRes.iv
              };
              
              console.log('发送登录请求数据:', requestData);
              
              post('/api/auth/wechat_login', requestData).then(res => {
                console.log('登录成功响应:', res);
                wx.hideLoading();
                
                // 保存token
                wx.setStorageSync('token', res.token);
                getApp().globalData.token = res.token;
                
                // 保存userId
                if (res.userId) {
                  wx.setStorageSync('userId', res.userId);
                } else if (res.user && res.user.id) {
                  wx.setStorageSync('userId', res.user.id);
                }
                
                // 保存完整用户信息到userInfo
                const user = res.user || res;
                let avatarFile = '';
                if (user.avatarUrl && user.avatarUrl.length > 0) {
                  avatarFile = user.avatarUrl.replace(/^.*[\\/]/, '');
                }
                const avatarPath = avatarFile ? '../../assets/avatar/' + avatarFile : userRes.userInfo.avatarUrl; // 使用微信头像
                const userInfo = {
                  avatarUrl: avatarPath,
                  nickname: user.nickname || user.username || userRes.userInfo.nickName || '未登录',
                  userId: user.userId || user.id || '',
                  active: user.active || 0,
                  activePercent: user.activePercent || 0,
                  phone: user.phone || '',
                  address: user.address || ''
                };
                wx.setStorageSync('userInfo', userInfo);
                
                wx.showToast({
                  title: '微信登录成功',
                  icon: 'success'
                });
                
                // 默认作为普通用户登录，微信登录通常不需要选择用户类型
                wx.setStorageSync('userType', 'user');
                wx.switchTab({ url: '/pages/mine/mine' });
              }).catch(err => {
                console.error('登录请求失败:', err);
                wx.hideLoading();
                
                let errorMessage = '微信登录失败';
                if (err.message) {
                  errorMessage = err.message;
                } else if (err.errMsg) {
                  errorMessage = err.errMsg;
                }
                
                wx.showToast({
                  title: errorMessage,
                  icon: 'none',
                  duration: 3000
                });
              });
            } else {
              console.error('获取code失败:', loginRes);
              wx.showToast({
                title: '微信登录失败：获取code失败',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            console.error('wx.login调用失败:', err);
            wx.showToast({
              title: '微信登录失败：wx.login调用失败',
              icon: 'none'
            });
          }
        });
      },
      fail: (err) => {
        console.error('获取用户资料失败:', err);
        wx.showToast({
          title: '您拒绝了授权',
          icon: 'none'
        });
      }
    });
  },

  // 新增：微信一键登录（旧版，bindgetuserinfo方式）
  onGetUserInfo(e) {
    if (e.detail.userInfo) {
      wx.login({
        success: (loginRes) => {
          if (loginRes.code) {
            wx.showLoading({
              title: '登录中...',
              mask: true
            });
            post('/api/auth/wechat_login', {
              code: loginRes.code,
              rawData: e.detail.rawData,
              signature: e.detail.signature,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv
            }).then(res => {
              wx.hideLoading();
              // 保存token
              wx.setStorageSync('token', res.token);
              getApp().globalData.token = res.token;
              // 保存userId
              if (res.userId) {
                wx.setStorageSync('userId', res.userId);
              } else if (res.user && res.user.id) {
                wx.setStorageSync('userId', res.user.id);
              }
              // 保存完整用户信息到userInfo
              const user = res.user || res;
              let avatarFile = '';
              if (user.avatarUrl && user.avatarUrl.length > 0) {
                avatarFile = user.avatarUrl.replace(/^.*[\\/]/, '');
              }
              const avatarPath = avatarFile ? '../../assets/avatar/' + avatarFile : e.detail.userInfo.avatarUrl; // 使用微信头像
              const userInfo = {
                avatarUrl: avatarPath,
                nickname: user.nickname || user.username || e.detail.userInfo.nickName || '未登录',
                userId: user.userId || user.id || '',
                active: user.active || 0,
                activePercent: user.activePercent || 0,
                phone: user.phone || '',
                address: user.address || ''
              };
              wx.setStorageSync('userInfo', userInfo);
              wx.showToast({
                title: '微信登录成功',
                icon: 'success'
              });
              // 默认作为普通用户登录，微信登录通常不需要选择用户类型
              wx.setStorageSync('userType', 'user');
              wx.switchTab({ url: '/pages/mine/mine' });
            }).catch(err => {
              wx.hideLoading();
              wx.showToast({
                title: err.message || '微信登录失败',
                icon: 'none'
              });
              console.error('微信登录失败:', err);
            });
          } else {
            wx.showToast({
              title: '微信登录失败：获取code失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '微信登录失败：wx.login调用失败',
            icon: 'none'
          });
          console.error('wx.login调用失败:', err);
        }
      });
    } else {
      wx.showToast({
        title: '获取用户信息失败，请升级微信版本',
        icon: 'none'
      });
    }
  },

  async handleLogin() {
    const { username, password, userTypes, userTypeIndex } = this.data
    if (!username || !password) {
      wx.showToast({
        title: '请输入用户名和密码',
        icon: 'none'
      })
      return
    }
    if (userTypeIndex === null) {
      wx.showToast({
        title: '请选择登录用户类型',
        icon: 'none'
      })
      return
    }
    try {
      let requestUrl = '/api/auth/login';
      let postData = { username, password, userType: userTypes[userTypeIndex] };
      // 新增：维修工登录逻辑
      if (userTypes[userTypeIndex] === '维修工') {
        requestUrl = '/api/technicians/login';
        // 自动判断输入的是手机号还是邮箱
        if (/^\d{11}$/.test(username)) {
          postData = { phone: username, password };
        } else if (username.indexOf('@') > -1) {
          postData = { email: username, password };
        } else {
          postData = { phone: username, password };
        }
      }
      console.log('正在发送登录请求到:', requestUrl);
      const res = await post(requestUrl, postData)
      // 保存token
      wx.setStorageSync('token', res.token)
      getApp().globalData.token = res.token
      // 保存userId
      if (res.userId) {
        wx.setStorageSync('userId', res.userId)
      } else if (res.user && res.user.id) {
        wx.setStorageSync('userId', res.user.id)
      }
      // 保存完整用户信息到userInfo
      const user = res.user || res;
      let avatarFile = '';
      if (user.avatarUrl && user.avatarUrl.length > 0) {
        avatarFile = user.avatarUrl.replace(/^.*[\\/]/, '');
      }
      const avatarPath = avatarFile ? '../../assets/avatar/' + avatarFile : '../../assets/images/default-avatar.png';
      const userInfo = {
        avatarUrl: avatarPath,
        nickname: user.nickname || user.username || user.name || '未登录',
        userId: user.userId || user.id || '',
        active: user.active || 0,
        activePercent: user.activePercent || 0,
        phone: user.phone || '',
        address: user.address || ''
      };
      wx.setStorageSync('userInfo', userInfo);
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      })
      console.log('当前选择的用户类型:', userTypes[userTypeIndex])
      if (userTypes[userTypeIndex] === '维修工') {
        console.log('即将跳转到工程师端');
        wx.setStorageSync('userType', 'worker');
        wx.setStorageSync('technicianInfo', user);
        wx.redirectTo({ url: '/pages/worker/index' });
      } else {
        console.log('即将跳转到用户端');
        wx.setStorageSync('userType', 'user');
        wx.switchTab({ url: '/pages/mine/mine' });
      }
    } catch (err) {
      console.error('登录请求失败或发生异常:', err);
      wx.showToast({
        title: err.message || '登录失败',
        icon: 'none'
      })
    }
  },

  goRegisterUser() {
    wx.navigateTo({ url: '/pages/register/register?type=user' })
  },
  goRegisterWorker() {
    wx.navigateTo({ url: '/pages/register/register?type=worker' })
  },

  goToForgotPassword() {
    wx.navigateTo({ url: '/pages/forgotPassword/forgotPassword' })
  }
}) 